package stack;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2022-06-30
 * Time: 9:47
 */
public class MyStack<E> {
    public E[] elem;
    public int usedSize;
    public MyStack(){
        this.elem=(E[])new Object[1];
    }
    public void push(E data){
        if(isFull()){
            this.elem= Arrays.copyOf(this.elem,2*this.elem.length);
        }
        this.elem[this.usedSize++]=data;
    }
    public boolean isFull(){
        return this.usedSize==this.elem.length;
    }
    public E pop(){
        if(empty()){
            throw new NullPointerException("栈为空");
        }
        E ret=this.elem[usedSize-1];
        this.elem[usedSize-1]=null;//栈内存中存储引用类型的时候要把它置为null
        usedSize--;
        return ret;
    }
    public E peek(){
        if(empty()){
            throw new ArrayIndexOutOfBoundsException("栈为空");
        }
        return this.elem[usedSize-1];
    }
    public boolean empty(){
        return this.usedSize==0;
    }
    public int size(){
        return this.usedSize;
    }
}
